Word Break
Question
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
Analysis
- 数组f[i]表示截止到第i个字符是否满足wordbreak的条件
- 外层循环从1开始,循环对f[i]进行赋值
- 内层循环范围为0-i,检查该部分字符串是否存在一个节点j可以使得其满足wordbreak条件
- 最终返回f[s.length]
Code
|
|
WordBreak II
Question
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
Analysis
- 从1开始循环,看[1,length]范围内的子串t是否在字典内,假如在字典内进入递归
- 对[0,i]范围内的子串进行处理,并返回former
- 假如former不为空,将former中的串+空格+tmp加入res中,并在最后返回
Code
|
|